package top.leyi.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import top.leyi.entity.Talk;
import top.leyi.entity.User;
import top.leyi.exception.NoSuchAuthException;
import top.leyi.exception.NotSuchUserIdException;
import top.leyi.mapper.UserMapper;

import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

/**
 * @desc 使用aop为说说进行权限认证，
 * 1 ： 用户是否存在
 * 2 ： 用户是否具有以下权限
 *
 *     超级用户   id：19  token：4ce2655b261752c951b34429073547a8
 */
@Component
@Aspect
public class TalkAuthAop {

    @Autowired
    UserMapper userMapper;

     @Pointcut(value = "execution(public * top.leyi.IService.ITalkService.addTalk(..))    ||" +
                       "execution(public * top.leyi.IService.ITalkService.commentTalk(..)) ||" +
                       "execution(public * top.leyi.IService.ITalkService.goodTalk(..)) ")
     public void welog(){
     }


//     @Before(value = "welog()")
//     public void speak(JoinPoint jp)throws  NoSuchAuthException, NotSuchUserIdException {
//           String[] signatures = jp.getSignature().toString().split("\\.");
//           String operation = signatures[signatures.length - 1].split("\\(")[0];
//
//           Talk talk  = (Talk) jp.getArgs()[0];
//           User user = (User) jp.getArgs()[1];
//
//           user = userMapper.queryOneUserWithToken(user);
//           if(user == null){
//               throw new NotSuchUserIdException();
//           }
//           List<String> powers = userMapper.queryOwnPrivilege(user);
//           for(String power: powers){
//               if(power.equals(operation)){
//                   return;
//               }
//           }
//           throw new NoSuchAuthException();
//     }


    @Around("welog()")
    public Object   doAround(ProceedingJoinPoint jp) throws  NoSuchAuthException, Throwable{
        Object o = null;
        String[] signatures = jp.getSignature().toString().split("\\.");
        String operation = signatures[signatures.length - 1].split("\\(")[0];

        Talk talk  = (Talk) jp.getArgs()[0];
        User user = (User) jp.getArgs()[1];

        user = userMapper.queryOneUserWithToken(user);
        /*
            如果没有这个用户，则抛出异常
         */
        if(user == null){
            throw new NotSuchUserIdException();
        }
        List<String> powers = userMapper.queryOwnPrivilege(user);
        boolean flag = false;
        for(String power: powers){
            if(power.equals(operation)){
                flag = true;
            }
        }
        if(!flag)
            throw new NoSuchAuthException("缺乏权限，请先对必要的个人信息进行完善（班级，用户名）");

        return jp.proceed(new Object[]{talk, user});
    }


}
